package com.highbury5.server;

import com.highbury5.blog.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

import java.io.*;
import java.util.Properties;

public class WebServer {

    private Log log = LogFactory.getLog(this.getClass());

    private static final String WEB_CONFIG = "web.property";

    public void start(){
        log.info("jetty start...");

        //获取配置信息
        InputStream in = null;
        Properties webConfig = new Properties();
        try{
            in = new BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream(WEB_CONFIG));
            webConfig.load(in);
        }catch (IOException e){
            log.error("加载错误信息文件异常:" + StringUtil.getErrorStack(e));
            throw new RuntimeException(e);
        }finally {
            if(in != null){
                try {
                    in.close();
                }catch (Exception e){
                    log.error(e);
                }
            }
        }

        int port = Integer.parseInt(webConfig.getProperty("port"));
        String path = webConfig.getProperty("path");
        String webXmlPath = webConfig.getProperty("webXmlPath");
        String resourcePath = webConfig.getProperty("resourcePath");
        log.debug("webserver port : " + port);
        log.debug("webserver path : " + path);
        log.debug("webserver webXmlPath : " + webXmlPath);
        log.debug("webserver resourcePath : " + resourcePath);

        Server server = new Server(port);

        WebAppContext context = new WebAppContext();
        context.setContextPath(path);
        context.setDescriptor(webXmlPath);
        context.setResourceBase(resourcePath);
        server.setHandler(context);

        try {
            server.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
